<html>
<head>
<script type="text/javascript" src="/scripts/dom.js"></script>
<script type="text/javascript" src="/scripts/ajax.js"></script>
<script type="text/javascript">

function loadPlayers() {
	ajaxRequest("listplayers.jsp", function(json) {
		listPlayers(json);
	});
}
function clearPlayers() {
	ajaxRequest("clearplayers.jsp", function(json) {
		listPlayers(json);
	});
}
function registerPlayer() {
	var name = document.getElementById("name").value;
	var mail = document.getElementById("mail").value;
	var rank = document.getElementById("rank").value;

	ajaxRequest("register.jsp?name="+name+"&mail="+mail+"&rank="+rank, function(json) {
		listPlayers(json);
	});
}

function listPlayers(players) {
	removeAllChildrenOfId("players");
	for (var i = 0; i < players.length; ++i) {
		var player = players[i];
		appendChildToId("players", buildPlayerRow(player));
	}
}
function buildPlayerRow(player) {
	var playerRow = document.createElement("tr");
	playerRow.appendChild(buildTableCell(buildTextNode(player.id)));
	playerRow.appendChild(buildTableCell(buildTextNode(player.name)));
	playerRow.appendChild(buildTableCell(buildTextNode(player.mail)));
	playerRow.appendChild(buildTableCell(buildTextNode(player.rank)));
	playerRow.appendChild(buildTableCell(buildTextNode(buildGameList(player.games))));

	playerRow.appendChild(buildTableCell(buildButton("Delete", function() {})));
	return playerRow;
}
function buildGameList(games) {
	var list = ".";
	for (var i = 0; i < games.length; ++i) {
		var game = games[i];
		list += game;
		if (i < games.length -1) list += ", ";
	}
	return list;
}

window.onload = function() { loadPlayers(); }
</script>
</head>
<body>
<h1>Players Info</h1>
<table border>
<tr>
<th>Id</th>
<th>Name</th>
<th>Mail</th>
<th>Rank</th>
<th>Games</th>
</tr>
<tbody id="players">
</tbody>
<tfoot>
<tr>
<td><input id="id" /></td>
<td><input id="name" /></td>
<td><input id="mail" /></td>
<td><input id="rank" /></td>
<td><input id="games" /></td>
</tr>
</tfoot>
</table>

<button onclick="loadPlayers()"/>Get Players</button>
<button onclick="clearPlayers()"/>Clear Players</button>
<button onclick="registerPlayer()"/>Create Player</button>
<br>
<a href="register.jsp">Register</a>
<a href="listplayers.jsp">List Players</a>
<a href="clearplayers.jsp">Clear Players</a>
</body>
</html>
